#include "EventLoopThreadPool.h"
#include "Thread.h"
#include "EventLoopThread.h"


EvenLoopThreadPool::EvenLoopThreadPool(EventLoop *baseLoop, const std::string &name)
    : bashLoop_(baseLoop), name_(name), started_(false), numThreads_(0), next_(0)
{
}

EvenLoopThreadPool::~EvenLoopThreadPool()
{
    // 不需要手动析构，因为threads是栈的对象，随着loop函数结束，会自动释放
}

void EvenLoopThreadPool::start(const ThreadInitCallback &cb)
{
    for (int i = 0; i < numThreads_; i++)
    {
        std::string name = name_ + std::to_string(i);
        auto a = new EventLoopThread(cb, name);
        std::unique_ptr<EventLoopThread> loopThread(a);
        loops_.push_back(loopThread->startLoop());
        threads_.emplace_back(std::move(loopThread));
        
    }

    if (numThreads_ == 0 && cb)
    {
        cb(bashLoop_);
    }
    
}

EventLoop *EvenLoopThreadPool::getNextLoop()

{
    EventLoop* loop = bashLoop_;
    if (loops_.empty())
    {
        return loop;   
    }
    loop = loops_[next_++];
    if (next_ >= loops_.size())
    {
        next_ = 0;
    }
    return loop;
    
}

std::vector<EventLoop *> EvenLoopThreadPool::getAllLoops()
{
    
    if (loops_.empty())
    {
        return std::vector<EventLoop*>(1, bashLoop_);
    }

    return loops_;
    
}
